package com.example.generator;

import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine;

import java.nio.file.Paths;
import java.sql.Types;

/**
 * 代码生成工具类：根据数据库表生成相应的entity、mapper、mapper.xml、service、serviceImpl、controller
 * 请修改url中的数据库名，以及数据库连接的用户名和密码
 */
public class CodeGenerator {
    public static void main(String[] args) {
        FastAutoGenerator.create("jdbc:mysql://localhost:3306/case-manager?useSSL=false&useUnicode=true&characterEncoding=UTF-8",
                        "root", "123456")
                .globalConfig(builder -> builder
                        .author("iKun")
                        .outputDir(Paths.get(System.getProperty("user.dir")) + "/src/main/java")
                        .commentDate("yyyy-MM-dd")
                )
                .dataSourceConfig(builder ->
                        builder.typeConvertHandler((globalConfig, typeRegistry, metaInfo) -> {
                            int typeCode = metaInfo.getJdbcType().TYPE_CODE;
                            if (typeCode == Types.SMALLINT) {
                                // 自定义类型转换
                                return DbColumnType.INTEGER;
                            }
                            return typeRegistry.getColumnType(metaInfo);
                        })
                )
                .packageConfig(builder -> builder
                        .parent("com.example")
                        .entity("entity")
                        .mapper("mapper")
                        .service("service")
                        .serviceImpl("service.impl")
                        .xml("mapper.xml")
                )
                .strategyConfig(builder -> builder
                        .entityBuilder()
                        .enableLombok()
                        .javaTemplate("/templates/entity.java") // 设置实体类模板
                        // .disable() // 禁用实体类生成
                        .serviceBuilder()
                        // .disableService() // 禁用 Service 层生成
                        .serviceTemplate("/templates/service.java") // 设置 Service 模板
                        .serviceImplTemplate("/templates/serviceImpl.java") // 设置 ServiceImpl 模板
                        .build()
                )
                .templateEngine(new VelocityTemplateEngine())
                .execute();
    }
}